package com.sixbro.authorization.security.exception;

import com.sixbro.common.domain.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter;
import org.springframework.security.oauth2.provider.error.DefaultOAuth2ExceptionRenderer;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;

/**
 * <p>
 *  {@link OAuth2AuthenticationProcessingFilter}
 *  {@link DefaultOAuth2ExceptionRenderer}
 * </p>
 *
 * @author: Mr.Lu
 * @since: 2021/6/15 17:33
 */
@Slf4j
public class OAuth2WebResponseExceptionTranslator implements WebResponseExceptionTranslator {

    @Override
    public ResponseEntity translate(Exception e) throws Exception {
        log.error("认证服务器异常",e);

        ApiResponse response = resolveException(e);

        return new ResponseEntity(response, HttpStatus.valueOf(response.getCode()));
    }

    /**
     * 构建返回异常
     * @param e
     * @return
     */
    private ApiResponse resolveException(Exception e) {

        int httpStatus = HttpStatus.UNAUTHORIZED.value();
        if (e instanceof UnsupportedGrantTypeException) {

        } else if (e instanceof InvalidGrantException) {

        }

        ApiResponse<Object> failResponse = ApiResponse.failed(e.getMessage());
        failResponse.setCode(String.valueOf(httpStatus));

        return failResponse;
    }
}